<script setup lang="ts">
import { getGoodsByIdAPI, getMemberAddressAPI, postMemberCartAPI } from '@/services'
import type { AddressItem, GoodsResult } from '@/types'
import type { SwiperOnChange } from '@uni-helper/uni-app-types'
import type { UniPopupInstance } from '@uni-helper/uni-ui-types'
import type {
  SkuPopupEvent,
  SkuPopupInstance,
  SkuPopupLocaldata,
} from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref, computed } from 'vue'
import AddressPanel from './components/AddressPanel.vue'
import ServicePanel from './components/ServicePanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { useMemberStore } from '@/stores'
import { storeToRefs } from 'pinia'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

interface Props {
  id: string
}
const query = defineProps<Props>()

// 商品详细信息
const goods = ref<GoodsResult>()
// 商品规格信息
const skuLocalData = ref({} as SkuPopupLocaldata)
// 获取商品详情和规格信息
const getGoodsByIdData = async () => {
  const res = await getGoodsByIdAPI(query.id)
  goods.value = res.result
  skuLocalData.value = {
    _id: res.result.id,
    name: res.result.name,
    goods_thumb: res.result.mainPictures[0],
    spec_list: res.result.specs.map((v) => ({ name: v.name, list: v.values })),
    sku_list: res.result.skus.map((v) => ({
      _id: v.id,
      goods_id: res.result.id,
      goods_name: res.result.name,
      image: v.picture,
      price: v.price * 100, // 注意：需要乘以100
      stock: v.inventory,
      sku_name_arr: v.specs.map((vv) => vv.valueName),
    })),
  }
}
// 获取收货地址列表
const addressList = ref<AddressItem[]>([])
const getMemberAddressList = async () => {
  const res = await getMemberAddressAPI()
  addressList.value = res.result
}
const isLoading = ref(false)
const memberStore = useMemberStore()
const { isLogin } = storeToRefs(memberStore)
onLoad(async () => {
  isLoading.value = true
  await getGoodsByIdData()
  isLoading.value = false
})
onShow(() => {
  if (isLogin.value) {
    // 作用1：页面刚打开时，用户已登录则自动获取收货地址
    // 作用2：用户已登录时，商品详情页从后台进入前台，重新获取收货地址
    getMemberAddressList()
  }
})

/* 商品轮播图交互 */
const currentIndex = ref(0)
const onSwiperChange: SwiperOnChange = (e) => {
  currentIndex.value = e.detail.current
}
const onImagePreview = (current: string) => {
  uni.previewImage({
    urls: goods.value!.mainPictures,
    current,
  })
}

/* SKU规格弹窗交互 */
const skuPopupRef = ref<SkuPopupInstance | null>(null)
// 选中的商品规格信息
const selectArrText = computed(
  () => skuPopupRef.value?.selectArr?.join(' ').trim() || '请选择商品规格',
)
const isShowSku = ref(false)
// SKU按钮模式
enum SkuMode {
  Both = 1,
  Cart = 2,
  Buy = 3,
}
const mode = ref<SkuMode>(SkuMode.Both)
const openSkuPopup = (val: SkuMode) => {
  isShowSku.value = true
  mode.value = val
}
// 加入购物车
const onAddCart = async (e: SkuPopupEvent) => {
  await postMemberCartAPI({ skuId: e._id, count: e.buy_num })
  uni.showToast({ icon: 'success', title: '添加成功' })
  isShowSku.value = false
}
// 立即购买
const onBuyNow = (e: SkuPopupEvent) => {
  uni.navigateTo({
    url: `/pagesOrder/create/create?skuId=${e._id}&count=${e.buy_num}&addressId=${selectAddressData.value?.id}`,
  })
  isShowSku.value = false
}

/* 地址、服务弹窗交互 */
const popupRef = ref<UniPopupInstance | null>(null)
const popupName = ref<'address' | 'service'>()
const openPopup = (name: typeof popupName.value) => {
  // 选择收货地址时用户未登录，弹窗提示用户前往登录
  if (!isLogin.value && name === 'address') {
    return uni.showModal({
      title: '提示',
      content: '获取收货地址需要用户先登录，您是否前往登录？',
      confirmColor: '#27BA9B',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/login/login' })
        }
      },
    })
  }
  popupName.value = name
  popupRef.value?.open?.()
}
// 选中的收货地址信息
const selectAddressData = ref<AddressItem>()
const selectAddressText = computed(() =>
  selectAddressData.value?.id
    ? `${selectAddressData.value?.fullLocation} ${selectAddressData.value?.address}`
    : '请选择收获地址',
)
const onAddressPanelClose = (address?: AddressItem) => {
  if (address) {
    selectAddressData.value = address
  }
  popupRef.value?.close?.()
}
</script>

<template>
  <!-- 骨架屏 -->
  <PageSkeleton v-if="isLoading" />
  <template v-else>
    <scroll-view class="viewport" scroll-y enable-back-to-top>
      <!-- 基本信息 -->
      <view class="goods">
        <!-- 商品主图 -->
        <view class="preview">
          <swiper circular @change="onSwiperChange">
            <swiper-item v-for="item in goods?.mainPictures" :key="item">
              <image class="image" mode="aspectFill" :src="item" @tap="onImagePreview(item)" />
            </swiper-item>
          </swiper>
          <view class="indicator">
            <text class="current">{{ currentIndex + 1 }}</text>
            <text class="split">/</text>
            <text class="total">{{ goods?.mainPictures.length }}</text>
          </view>
        </view>
        <!-- 商品简介 -->
        <view class="meta">
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ goods?.price }}</text>
          </view>
          <view class="name ellipsis">{{ goods?.name }}</view>
          <view class="desc"> {{ goods?.desc }} </view>
        </view>
        <!-- 操作面板 -->
        <view class="action">
          <view class="item arrow" @tap="openSkuPopup(SkuMode.Both)">
            <text class="label">选择</text>
            <text class="text ellipsis">{{ selectArrText }}</text>
          </view>
          <view class="item arrow" @tap="openPopup('address')">
            <text class="label">送至</text>
            <text class="text ellipsis">{{ selectAddressText }}</text>
          </view>
          <view class="item arrow" @tap="openPopup('service')">
            <text class="label">服务</text>
            <text class="text ellipsis"> 无忧退 快速退款 免费包邮 </text>
          </view>
        </view>
      </view>
      <!-- 商品详情 -->
      <view class="detail panel">
        <view class="title">
          <text>详情</text>
        </view>
        <view class="content">
          <!-- 属性详情 -->
          <view class="properties">
            <view class="item" v-for="item in goods?.details.properties" :key="item.name">
              <text class="label">{{ item.name }}</text>
              <text class="value">{{ item.value }}</text>
            </view>
          </view>
          <!-- 图片详情 -->
          <image
            class="image"
            mode="widthFix"
            :src="item"
            v-for="item in goods?.details.pictures"
            :key="item"
          />
        </view>
      </view>
      <!-- 同类推荐 -->
      <view class="similar panel">
        <view class="title">
          <text>同类推荐</text>
        </view>
        <view class="content">
          <navigator
            v-for="item in goods?.similarProducts"
            :key="item.id"
            class="goods"
            hover-class="none"
            :url="`/pages/goods/goods?id=${item.id}`"
          >
            <image class="image" mode="aspectFill" :src="item.picture" />
            <view class="name ellipsis">{{ item.name }}</view>
            <view class="price">
              <text class="symbol">¥</text>
              <text class="number">{{ item.price }}</text>
            </view>
          </navigator>
        </view>
      </view>
    </scroll-view>
    <!-- 底部工具栏 -->
    <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      <view class="icons">
        <button class="icons-button"><text class="icon-heart"></text>收藏</button>
        <!-- #ifdef MP-WEIXIN -->
        <button class="icons-button" open-type="contact">
          <text class="icon-handset"></text>客服
        </button>
        <!-- #endif -->
        <navigator
          class="icons-button"
          hover-class="none"
          open-type="navigate"
          url="/pages/cart/cart-page"
        >
          <text class="icon-cart"></text>购物车
        </navigator>
      </view>
      <view class="buttons">
        <view class="addcart" @tap="openSkuPopup(SkuMode.Cart)"> 加入购物车 </view>
        <view class="buynow" @tap="openSkuPopup(SkuMode.Buy)"> 立即购买 </view>
      </view>
    </view>
    <!-- SKU规格弹窗 -->
    <vk-data-goods-sku-popup
      ref="skuPopupRef"
      v-model="isShowSku"
      :localdata="skuLocalData"
      :mode="mode"
      add-cart-background-color="#FFA868"
      buy-now-background-color="#27BA9B"
      :actived-style="{
        color: '#27BA9B',
        borderColor: '#27BA9B',
        backgroundColor: '#E9F8F5',
      }"
      @add-cart="onAddCart"
      @buy-now="onBuyNow"
    />
    <!-- 地址、服务弹窗 -->
    <uni-popup ref="popupRef" type="bottom" background-color="#fff">
      <AddressPanel
        v-if="popupName === 'address'"
        :list="addressList"
        @close="onAddressPanelClose"
      />
      <ServicePanel v-if="popupName === 'service'" @close="popupRef?.close" />
    </uni-popup>
  </template>
</template>

<style lang="scss">
@import './styles/goods.scss';
</style>
